package cn.tedu._03vehicle.controller;

import cn.tedu._03vehicle.base.response.JsonResult;
import cn.tedu._03vehicle.base.utils.CacheUtil;
import cn.tedu._03vehicle.mapper.NoticeMapper;
import cn.tedu._03vehicle.pojo.vo.NoticeListVO;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.io.Serializable;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * RestController: Controller + ResponseBody;
 * Slf4j: Lombok注解;
 * Api: Knife4j注解;
 * GetMapping、PostMapping、PutMapping、DeleteMapping: Spring MVC注解;
 */
@Slf4j
@RestController
@Api(tags = "03.通知管理模块")
@RequestMapping("/v1/notice/")
public class NoticeController {
    @Autowired
    private NoticeMapper noticeMapper;

    @Autowired
    private RedisTemplate<String, Serializable> redisTemplate;

    @Autowired
    private CacheUtil cacheUtil;

    @GetMapping("list")
    @ApiOperation("公告列表")
    @ApiOperationSupport(order = 10)
    public JsonResult noticeList(){
        /*
            缓存设计-字符串: {"notice_index": '[{"id":"","title":""},{},...]'}
            1.查询Redis中是否存在首页数据[GET key];
              1.1 缓存中存在,直接返回结束;
              1.2 缓存中不存在
                  1.2.1 到MySQL中查询首页数据;
                  1.2.2 设置到Redis中[SET key value];
                  1.2.3 返回响应;
             提示[过期时间]:
             ValueOperations<String, Serializable> ops = redisTemplate.opsForValue();
             ops.set("xxx", "xxx", 30, TimeUnit.SECONDS);
         */
        //1.缓存中获取数据
        //ValueOperations<String, Serializable> ops = redisTemplate.opsForValue();
        //Serializable redisData = ops.get("notice_list");

        Serializable redisData = cacheUtil.get("notice_list");

        //2.判断
        //2.1 缓存中存在
        if (redisData != null){
            log.debug("首页数据来自Redis数据库");
            return JsonResult.ok(redisData);
        }
        //2.2缓存中不存在
        log.debug("首页数据来自MySQL数据库");
        List<NoticeListVO> noticeListVOS = noticeMapper.noticeList();
        //ops.set("notice_list", (Serializable) noticeListVOS, 30, TimeUnit.SECONDS);
        cacheUtil.setExpire("notice_list", (Serializable) noticeListVOS, 30);

        return JsonResult.ok(noticeListVOS);
    }
}












